<template>
	<view class="contract-edit">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{isEditContract ? '编辑合同' : '添加合同'}} </block>
		</cu-custom>
		<form>
			<!-- ====================== 合同信息 ========================  -->
			<view>
				<view class="cu-bar text-gray">
					<view class="action">
						 合同信息
					</view>
				</view>
				<view class="cu-form-group">
					<view class="title"><text class="icon-ruzhuyixiang-yixiangbianhao"></text> 合同编号:</view>
					<input  name="input" v-model="contract.ContractCode" placeholder="请输入合同编号"></input>
				</view>
				<view class="cu-form-group">
					<view class="title"><text class="icon-jine1"></text>交易金额(元):</view>
					<input placeholder="请输入交易金额,单位(元)" name="input" v-model="contract.Amount"></input>
				</view>
				<view class="cu-form-group">
					<view class="title"><text class="icon-riqi"></text>移交日期</view>
					<picker mode="date" :value="contract.HandoverDate"  @change="DateChange">
						<view class="picker">
							{{contract.HandoverDate}}
						</view>
					</picker>
				</view>
			</view>
			
			<!-- ====================== 房屋信息 ========================  -->
			<view class="house">
				<view class="cu-bar text-gray">
					<view class="action">房屋信息</view>
				</view>
				<view class="cu-form-group">
					<view class="title"><text class="icon-0301renxiang"></text>房屋权利人</view>
					<text> {{house.ApplicantName}} </text>
				</view>	
				<view class="cu-form-group">
					<view class="title"><text class="icon-2shenfenzhenghaoma"></text>权利人身份证号</view>
					<text>{{house.CertificateNumber}}</text>
				</view>	
				<view class="cu-form-group">
					<view class="title"><text class="icon-zhishichanquan"></text>产权号</view>
					<text>{{house.CertificateNo}}</text>
				</view>	
				<view class="cu-form-group address">
					<view class="title"><text class="cuIcon-location"></text>地址</view>
					<text>{{house.Address}}</text>
				</view>
				<view class="cu-form-group">
					<view class="title"><text class="icon-building"></text>建筑面积</view>
					<text>{{house.ConstructionArea}}平方米</text>
				</view>
				<view class="cu-form-group">
					<view class="title"><text class="icon-mianji-xian"></text>室内建筑面积</view>
					<text>{{house.ComprisingArea}}平方米</text>
				</view>				
			</view>
		</form>
		
		
		<!-- ====================== 当事人 ========================  -->
		
		<view>
			<view>
				<view class="cu-bar bg-white   margin-top">
					<view class="action"><text class="cuIcon-title text-blue"></text>卖方人员</view>
					<view class="action">
						<button class=" cu-btn cu-tag line-blue round"  @click="peopleShowMadal" :data-target="2">
							<text class="cuIcon-add"></text>添加</button>
					</view>
				</view>
				
				<view class="cu-bar   padding-left-xs padding-right-xs text-gray" style="flex-wrap:wrap;">
					<block v-for="(item, index) in PeopleList" :key="index">
						<view class=" margin-xs padding-sm flex bg-white solid radius" v-if="item.Role == 2"  @click="updatePeople(item, 2)">
							<view class="cuIcon-friendfill text-blue"></view>
							<view class="padding-left-xs padding-right-xs">{{ item.Name }}:</view>
							<view>{{ _Property[item.Property] }}</view>
							<text class="cuIcon-close text-red  cu-tag badge" @click.stop="deletePeople(item)"></text>
						</view>						
					</block>
				</view>
			</view>
			
			<view>
				<view class="cu-bar bg-white   margin-top">
					<view class="action ">
						<text class="cuIcon-title text-blue"></text>买方人员
					</view>
					<view class="action ">
						<button class=" cu-btn cu-tag line-blue round"  @click="peopleShowMadal" :data-target="1">
							<text class="cuIcon-add"></text>添加</button>					
					</view>
				</view>			
				
				<view class="cu-bar   padding-left-xs padding-right-xs text-gray" style="flex-wrap:wrap;">
					<block v-for="(item, index) in PeopleList" :key="index">
						<view class=" margin-xs padding-sm flex bg-white solid radius" v-if="item.Role == 1"  @click="updatePeople(item, 1)">
							<view class="cuIcon-friendfill text-blue"></view>
							<view class="padding-left-xs padding-right-xs">{{ item.Name }}:</view>
							<view>{{ _Property[item.Property] }}</view>
							<text class="cuIcon-close text-red  cu-tag badge" @click.stop="deletePeople(item)"></text>
						</view>						
					</block>
				</view>				
			</view>
		</view>

		<view class="padding">
			<button class="cu-btn block bg-blue margin-tb-sm lg disabled"  @click="contractGenerate">
				 合同生成</button>
		</view>
		
		<!-- ================= 买受人 =================  -->
		<view v-if="modalName==='people'">
			<view class="cu-modal show">
				<PeopleEdit @hideModal="hideModal" :member="room.CS_RoomMember" :roleType="roleType" @change="changePeople" :currentPeople="currentPeople" ></PeopleEdit>
			</view>	
		</view>
			
		<load-progress :showProgress="showProgress"></load-progress>	
	</view>
</template>

<script>
	import { cardid } from "@/common/utils/validate.js"
	import { addSignRoomContract, getContractInfo, editContract } from '@/common/api/zft-contract.js'
	import { getHouseInfo,  getSignRoomInfo } from '@/common/api/zft.js'
	import { Property, Role } from '@/common/config/zft.js'
	import PeopleEdit from '@/components/contract/people-edit.vue'
	export default {
		components: { PeopleEdit }, 
		data() {
			let currentDate = this.getDate({format: true})
			return {
				// 有编辑和生成
				isEditContract: false,
				loading: false,
				modalName: '',
				showProgress: false,
				contract: {
					// title: '',
					ContractCode: '',
					Amount: '',
					HandoverDate: currentDate, // 移交日期
					// obligeeName: '', // 权利人
					// commonProprietorName: '', // 共有人,
					// peopleName: '', // 买受人
				},
				location: '',
				house: {
					obligeeIdcard: '', // 权利人身份证号
					qzNum: '',
					location: '',
					buildArea: '',
					insideBuildArea: '',
				},
				room: '',
				peopleIndex: 0,
				peopleNature: ['权利人', '共有人'],
				peopleNatureIndex: 0,
				roleType: 1, // <!-- 角色 1: 买受人 2: 出卖人 -->
				PeopleList: [],
				currentPeople: {},
				
				//、、、、、、、、、、、、、、、、、、、、//
				signId: '',
				PeopleConfig: {
				    Userid: '',
				    Address: '',
				    Phone: '',
					Name: '',
				    Remarks: '',
				    Role: 1,
				    Property: 1,
				    IsAgent: false,
				},
				roomId: '',
				
			}
		},
		computed: {
			user() {
				return this.$store.state.user.userList[0]
			},
			_Property() {
				return Property
			},
			_Role() {
				return Role
			}
		},
		onLoad (route) {
			console.log(' this.user: ', this.user)
			console.log(this.$transmit.get())
			console.log('route', route)
			if (route.signId && route.roomId) {
				this.isEditContract = true
				this.SignId = route.signId
				this.roomId = route.roomId
				this.getContractInfo()
				this.getSignRoomInfo()
			}
			else {
				let s = this.$transmit.get()				
				if (s && s.to === 'contractEdit') {
					this.house = s.house
					this.room = s.room
					console.log(' this.house: ', this.house)
					console.log(' this.room: ', this.room)
				} else {
					this.showToast('当前页面存在错误，请关闭当前页面重试！')
				}
			}
		},
		watch: {
			// 'contract.money'(value){
			// 	// this.contract.money = value.replace(/\D/g,'').replace(/....(?!$)/g,'$& ')
			// 	this.contract.money = value.replace(/\D/g,'').replace(/...(?!$)/g,'$&,')
			// }
		},
		methods: {
			/************************************************
				第一次生成合同
			************************************************/
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			
			// 添加人员
			peopleShowMadal(e) {
				this.roleType =  parseInt(e.currentTarget.dataset.target)
				this.currentPeople = {}
				this.modalName = 'people'
			},
			DateChange(e) {
				this.contract.HandoverDate = e.detail.value
			},
			pickerChange(e, key) {
				this[key] = parseInt(e.detail.value)
			},

			// 校验
			verify() {
				return true;
				console.log('this.house.obligeeIdcard', typeof this.house.obligeeIdcard)
				let res = cardid(this.house.obligeeIdcard)
				console.log('res', res)
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
			
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			
			
			// 合同生成
			contractGenerate() {
				
				// 验证相关操作
				if (!this.contract.ContractCode) {
					this.showToast('请输入有效的合同编号')
					return
				} 
				if (!this.contract.Amount || this.contract.Amount < 1000) {
					this.showToast('交易金额太少，请重新输入')
					return
				}
				
				uni.showModal({
					title: '温馨提示',
					content: '请确保合同信息正确',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						// 接口，提交合同基本信息
						if (res.confirm) {
							if (this.isEditContract) {
								this.addContractSubmite()
							} else {
								this.editContractSubmite()
							}
							
						}
					}
				})				
			},
			
			// 修改人员信息
			updatePeople(m, roleType) {
				// this.
				console.log('当前人员信息', m)
				this.roleType = roleType
				this.currentPeople = m
				this.$nextTick(() => {
					this.modalName = 'people'
				})
				
			},
			
			// 删除成员
			deletePeople(m) {
				let index = this.searchPeopleList(m)
				if (index>=0) {
					this.PeopleList.splice(index, 1)
				}
			},
			
			// 查找在数组中的下标
			searchPeopleList(m) {
				if (m && m.Userid) {
					for (let i = 0; i < this.PeopleList.length; i++) {
						if (this.PeopleList[i].Userid === m.Userid) {
							return i
						}
					}
					return -1
				} 
			},
			
			// 添加合同信息
			addContractSubmite() {
				if (this.loading) return
				
				// let tmp = JSON.parse(JSON.stringify(this.PeopleList))				
				// for (let i = 0; i < tmp.length; i++) {
				// 	delete tmp[i].Name
				// }
				
				let json = {
					// RoomId:	RoomId
					RoomId:	this.room.ID,		
					// ContractCode	合同编号
					ContractCode: this.contract.ContractCode,
					// Amount	合同金额
					Amount: Number(this.contract.Amount),
					// HandoverDate	交房日期,  DateTime
					HandoverDate: this.contract.HandoverDate,
					// SignDate	网签日期
					SignDate: '',
					// AddUserid	添加人Userid
					AddUserid: this.user.Userid,
					/*------------------*/
					People: this.PeopleList,
					// People	合同当事人  []
						// Userid	Userid
						// Address	地址
						// Phone	电话
						// Remarks	备注
						// Role	角色
						// Property	性质
						// IsAgent	是否代理人
					/*------------------*/
					/*------------------ */
					Appendices: '',
					// Appendices	合同附件（图片） []
						// Title	标题
						// Title: this.contract.title,
						// ImgCode	图片转Base64字符串
						// Url	URL
						// Group	分组 0：其它 9：合同word  1：签字页  2：合同信息页
						// Descript	说明
						// Remarks	备注	
					/*------------------ */				
				}
				
				
				this.loading = true
				// let body = { json: JSON.stringify(json) }
				console.log('合同生成， 提交的信息 ： ', json)
				/////////////////////////////
				// return true;
				/////////////////////////////////////
				addSignRoomContract(json).then(({data}) => {
					console.log('合同生成返回的信息:', data)
					if(data.msgcode == 1000) {
						// 合同网签
						uni.navigateTo({
							url: `/pages/contract-sign/contract-sign?SignId=${data.data.SignId}`
						})
					} else {
						this.showToast(data.msg)
					}
					this.loading = false
				}).catch(() => {
					this.loading = false
					this.showToast('生成合同失败，请稍后重试')
				})
			},
			
			// 改变合同当事人
			changePeople(e) {
				console.log('eeeeeeeeeee', e)
				if (e.isUpdate) {
					let index =  this.searchPeopleList(e.oldData)
					this.PeopleList[index] = e.data
				} else  {	
					let index = this.searchPeopleList(e.data)
					if (index !== -1)
						uni.showModal({
							title:'错误',
							content: `${e.data.Name} 已存在, 一个人只能添加一次`
						}) 
					else {
						this.PeopleList.push(e.data)
					}
				} 
				console.log('this.PeopleList', this.PeopleList)
			},
	
	
			/**********************************************************
				有合同需要编辑时
			*********************************************************/
			// 获取合同列表
			getContractInfo() {
				this.showProgress = true
				let s = {
					// SignId: ''	网签表id	string		是,
					SignId: this.SignId
				}
				getContractInfo(s).then(({data}) => {
					console.log('获取到的合同信息', data)
					if (data.msgcode == 1000) {
						this.contract = data.data
						this.contract.Amount = data.data.CS_SignZFT.Amount
						this.contract.HandoverDate = data.data.CS_SignZFT.HandoverDate
						// this.PeopleList = data.data.CS_SignPeople
						this.PeopleList = []
						for (let i = 0; i < data.data.CS_SignPeople.length; i++) {
							// let obj = Object.assign({}, this.PeopleConfig,  data.data.CS_SignPeople[i])
							this.PeopleList[i] = {}
							for (let prop in this.PeopleConfig) {
								this.PeopleList[i][prop] = data.data.CS_SignPeople[i][prop]
							}
							// this.PeopleList.push(obj)
						}
						// this.house = data.data.CS_SignHouse[0]
						console.log('this.PeopleList', this.PeopleList)
						
					} else {
						this.showToast(data.msg)
					}
				}).then(() => {
					this.showProgress = false
				})
			},
			
			// 得到签约室信息
			getSignRoomInfo() {
				this.showProgress = true
				getSignRoomInfo({roomId: this.roomId}).then(({data}) => {
					console.log('签约室信息信息:', data)
					this.showProgress = false
					if (data && data.msgcode == 1000) {
						this.room = data.data;
						let houseList = data.data.CS_RoomHouse;
						if (houseList && houseList.length > 0) {
							this.getHouseInfo(houseList[0])
						}
					} else this.showToast(data.msg)
				}).catch(() => {
					this.showProgress = false
				})
			},
			
			// 获取房屋信息
			getHouseInfo(item) {
				this.showProgress = true
				// identityNo=权利人证件号码&certificateNo=权证号
				let s = { 
					identityNo: item.MemberNo,
					certificateNo: item.CertificateNo
				}
				getHouseInfo(s).then(({data}) => {
					console.log('房屋信息 ：' , data)
					if (data.msgcode == 1000) {
						// this.houseInfoList = data.data
						this.house = data.data[0]
					} else {
						this.showToast(data.msg)
					}
				}).then(() => {
					this.showProgress = false
				})
			},
			
			// 编辑网签
			editContractSubmite () {
				if (this.isloading)return
				/**
				 0：其它
				 9：合同word
				 1：签字页
				 2：合同信息页
				*/
				// let signImgs = this.toImageInfo(this.otherImgList, 1)
				// let otherImgs = this.toImageInfo(this.signImageList, 2)
				// let Appendices = signImgs.concat(otherImgs)
				if (signImgs.length < 1) { 
					this.showToast(`请上传合同签字照片`)
					return
				}
				if (otherImgs.length < 1) {
					this.showToast(`合同信息及其他要件`)
					return
				}
					
				let json = {
					// SignId 网签表id
					SignId: this.SignId,
					// RoomId:	RoomId
					// RoomId:	this.contract.SignRoomId,	
					// ContractCode	合同编号
					// ContractCode: this.contract.ContractCode,
					// Amount	合同金额
					Amount: Number(this.contract.Amount),
					// HandoverDate	交房日期,  DateTime
					HandoverDate: this.contract.HandoverDate,
					// SignDate	网签日期
					SignDate: '',
					// AddUserid	添加人Userid
					// AddUserid: this.$store.state.user.userList[0].Userid,
					/*------------------*/
					People: this.PeopleList,
					// People	合同当事人  []
						// Userid	Userid
						// Address	地址
						// Phone	电话
						// Remarks	备注
						// Role	角色
						// Property	性质
						// IsAgent	是否代理人
					/*------------------*/
					/*------------------ */
					Appendices: this.room.CS_SignAppendices.length ? this.room.CS_SignAppendices : null ,
					// Appendices	合同附件（图片） []
						// Title	标题
						// Title: this.contract.title,
						// ImgCode	图片转Base64字符串
						// Url	URL
						// Group	分组 0：其它 9：合同word  1：签字页  2：合同信息页
						// Descript	说明
						// Remarks	备注	
					/*------------------ */				
				}
				
				
				this.loading = true
				// let body = { json: JSON.stringify(json) }
				console.log('合同网签， 提交的信息 ： ', json)
				/////////////////////////////
				// return true;
				/////////////////////////////////////
				editContract(json).then(({data}) => {	
					console.log('合同网签返回的信息:', data)	
					if(data.msgcode == 1000) {
						this.showToast('提交成功')
						
					} else {
						this.showToast(data.msg)
					}
					this.loading = false
				}).catch(() => {
					this.loading = false
					this.showToast('生成合同失败，请稍后重试')
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.cu-form-group .title {
		min-width: calc(4em + 15px);
		white-space: nowrap;
	}
	.house text {
		color: #555;
	}
	.house .address text {
		font-size: 28upx;
	}
	.cu-form-group .title {
		[class*="icon-"],
		[class*="cuIcon-"] {
			margin-right: 15upx;
		}
	}
</style>
